<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <span>{{ isLogin ? '登录' : '注册' }}</span>
        </div>
      </template>

      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item v-if="!isLogin" label="确认密码" prop="confirmPassword">
          <el-input
            v-model="formData.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" style="width: 100%" :loading="loading">
            {{ isLogin ? '登录' : '注册' }}
          </el-button>
        </el-form-item>

        <div class="switch-type">
          <el-link type="primary" @click="switchLoginType">
            {{ isLogin ? '没有账号？立即注册' : '已有账号？立即登录' }}
          </el-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { login, register } from '@/api/auth'
import { useUserStore } from '@/stores/user'
import { encryptPassword } from '@/utils/encrypt'
import { getUserInfo } from '@/api/user'
import Logger from '@/utils/logger'

import { storeToRefs } from 'pinia'

const router = useRouter()
const isLogin = ref(true)
const formRef = ref<FormInstance>()
const loading = ref(false)

const userStore = useUserStore()

const formData = reactive({
  username: '',
  password: '',
  confirmPassword: '',
})

const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== formData.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' },
  ],
})

const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true
        Logger.info('开始处理登录/注册请求')

        try {
          if (isLogin.value) {
            // 登录逻辑
            const response = await login({
              username: formData.username,
              password: encryptPassword(formData.password),
            })

            // 格式化打印完整的响应数据
            console.log('登录接口返回数据：', response)

            const { data } = response.data
            userStore.setUserInfo({
              token: data.token,
              username: data.user.username,
            })

            // 获取用户详细信息
            Logger.debug('开始获取用户信息')
            const userResponse = await getUserInfo()
            Logger.info('获取用户信息成功', userResponse.data)
            userStore.updateUserDetails(userResponse.data.data)

            ElMessage.success('登录成功')

            // 根据用户角色决定跳转页面
            const role = userStore.getUserRole(userResponse.data.data.role)
            console.log('用户角色：', role)
            if (role === 'super_admin' || role === 'admin') {
              // 管理员跳转到后台管理页面
              router.push('/admin')
            } else {
              // 普通用户跳转到前台页面
              window.location.href = '/'
            }
          } else {
            // 注册逻辑
            const response = await register({
              username: formData.username,
              password: encryptPassword(formData.password),
              confirmPassword: encryptPassword(formData.confirmPassword),
            })

            // 格式化打印完整的响应数据
            console.log('注册接口返回数据：', response)

            const { data } = response.data
            userStore.setUserInfo({
              token: data.token,
              username: data.user.username,
            })

            // 获取用户详细信息
            Logger.debug('开始获取用户信息')
            const userResponse = await getUserInfo()
            Logger.info('获取用户信息成功', userResponse.data)
            userStore.updateUserDetails(userResponse.data.data)

            ElMessage.success('注册成功')
            window.location.href = '/'
            // router.push('/')
          }
        } catch (error: any) {
          Logger.error('请求失败', {
            error: error.response?.data,
            status: error.response?.status,
            url: error.config?.url,
          })
          ElMessage.error(error.response?.data?.message || '操作失败')
        }
      }
    })
  } finally {
    loading.value = false
    Logger.info('请求处理完成')
  }
}

const switchLoginType = () => {
  isLogin.value = !isLogin.value
  formData.username = ''
  formData.password = ''
  formData.confirmPassword = ''
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-card {
  width: 400px;
}

.card-header {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
}

.switch-type {
  text-align: center;
  margin-top: 15px;
}
</style>
